package com.springboot.bigevent.conrtoller;

import com.springboot.bigevent.pojo.Result;
import com.springboot.bigevent.pojo.User;
import com.springboot.bigevent.service.UserService;
import com.springboot.bigevent.utils.JwtUtil;
import com.springboot.bigevent.utils.Md5Util;
import com.springboot.bigevent.utils.ThreadLocalUtil;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username ,@Pattern(regexp = "^\\S{5,16}$") String password){
        //查询用户是否已存在（查询时Service干的事，所以要声明一个Service对象）
        User u=userService.findByUsername(username);
        if(u==null){
            //若不存在，注册用户
            userService.register(username,password);
            return Result.success();
        }
        else{
            //若存在，报错
            return Result.error("用户名已被占用");

        }
    }

    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{5,16}$") String username ,@Pattern(regexp = "^\\S{5,16}$") String password){

        User u=userService.findByUsername(username);
        if(u==null){
            return Result.error("该用户不存在");
        }
        else{
            if(Md5Util.getMD5String(password).equals(u.getPassword())){
                 Map<String, Object> claims=new HashMap<>();
                 claims.put("id",u.getId());
                 claims.put("username",u.getUsername());
                String token=JwtUtil.genToken(claims);

                ValueOperations<String, String> ops=stringRedisTemplate.opsForValue();
                ops.set(token,token,12, TimeUnit.HOURS);
                return Result.success(token);
            }
            else{
                return Result.error("密码错误");
            }
        }
    }

    @GetMapping("/userInfo")
    public Result<User> userInfo( String token){
        //根据用户名查询用户信息
        Map<String, Object> map= ThreadLocalUtil.get();

        User user =userService.findByUsername((String)map.get("username"));
        return Result.success(user);
    }

    @PutMapping("/update")
    public Result update( @Validated @RequestBody User user){
        userService.update(user);
        return Result.success();
    }

    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@URL @RequestParam String avatarUrl){
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> params,@RequestHeader("Authorization") String token){


        if(!StringUtils.hasLength(params.get("old_pwd"))||!StringUtils.hasLength(params.get("new_pwd"))||
        !StringUtils.hasLength(params.get("re_pwd"))){
            return Result.error("缺少必要的参数");
        }
        Map<String,Object>map = ThreadLocalUtil.get();
        String username=(String)map.get("username");
        User user=userService.findByUsername(username);

        if(user.getPassword().equals(Md5Util.getMD5String(params.get("old_pwd")))){
            return  Result.error("原密码填写不正确");
        }
        if(!params.get("re_pwd").equals(params.get("new_pwd"))) {
            return  Result.error("两次输入的密码不同");
        }
        userService.updatePwd(params.get("new_pwd"));
        //更新密码后删除redis中的token
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ops.getOperations().delete(token);
        return Result.success();
    }
}
